package com.example.demo.controller;

import com.example.demo.common.AppResult;
import com.example.demo.common.ResultCode;
import com.example.demo.config.AppConfig;
import com.example.demo.model.Message;
import com.example.demo.model.User;
import com.example.demo.services.IMessageService;
import com.example.demo.services.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@Api(tags = "站内信接⼝")
@RestController
@RequestMapping("/message")
public class MessageController {
    // 注⼊业务层
    @Resource
    private IMessageService messageService;
    @Resource
    private IUserService userService;

    /**
     * 发送站内信
     *
     * @param receiveUserId 接收⽤⼾Id
     * @param content       内容
     * @return AppResult
     */
    @ApiOperation("发送站内信")
    @PostMapping("/send")
    public AppResult send(HttpServletRequest request,
                          @ApiParam(value = "接收⽤⼾Id") @RequestParam(value = "receiveUserId")
                          @NonNull Long receiveUserId,
                          @ApiParam(value = "站内信内容") @RequestParam(value = "content")
                          @NonNull String content) {


        // 1.当前登录用户的状态，如果是禁言状态不能发站内信
        HttpSession session=request.getSession(false);
        User user=(User) session.getAttribute(AppConfig.USER_SESSION);
        if(user==null || user.getState()==1)
        {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 2.不能给自己发站内信
        if(user.getId()==receiveUserId)
        {
            return AppResult.failed("不能给自己发送站内信");
        }
        // 3.校验接收者是否存在
        User receiveUser=userService.selectById(receiveUserId);
        if(receiveUser==null || receiveUser.getDeleteState()==1)
        {
            return AppResult.failed("接受者状态异常");
        }
        // 4.封装对象
        Message message=new Message();
        message.setContent(content);
        message.setReceiveUserId(receiveUserId);
        message.setPostUserId(user.getId());
        // 5.调用Service
        messageService.create(message);
        // 6.返回结果
        return AppResult.success("发送成功");

    }

    /**
     *获取未读消息个数
     * @param request
     * @return  AppResult<Integer>
     */
    @ApiOperation("获取未读数")
    @GetMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount (HttpServletRequest request) {
        // 1. 获取当前登录的用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 2. 调用Service
        Integer count = messageService.selectUnreadCount(user.getId());// 当前登录用户的Id就是接收者Id
        // 3. 返回结果
        return AppResult.success(count);
    }


    /**
     * 查询⽤⼾的所有站内信
     *
     * @return 站内信集合
     */
    @ApiOperation("查询用户的所有站内信")
    @GetMapping("/getAll")
    public AppResult<List<Message>> getAll (HttpServletRequest request) {
        // 1. 获取当前登录的用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 2. 调用Service
        List<Message> messages = messageService.selectByReceiveUserId(user.getId());
        // 3. 返回结果
        return AppResult.success(messages);
    }


    /**
     * 更新状态为已读
     *
     * @param id 站内信Id
     * @return AppResult<Message>
     */
    @ApiOperation("更新状态为已读")
    @PostMapping("/markRead")
    public AppResult markRead (HttpServletRequest request,
                               @ApiParam(value = "站内信Id") @RequestParam(value = "id") @NonNull Long id) {

        //根据ID查询站内信
        Message messages=messageService.selectById(id);

        //站内信是否存在
        if(messages==null || messages.getDeleteState()==1)
        {
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        //站内信是不是自己的
        HttpSession session=request.getSession(false);
        User user=(User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getId()!=messages.getReceiveUserId())
        {
            return AppResult.failed(ResultCode.FAILED);
        }

        messageService.updateStateById(id, (byte) 1);
        return AppResult.success();
    }

    /**
     * 回复站内信
     * * @param repliedId 要回复的站内信Id
     *  * @param content 站内信的内容
     *  * @return AppResult
     */
    @ApiOperation("回复站内信")
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,
                           @ApiParam("要回复的站内信Id") @RequestParam("repliedId") @NonNull Long repliedId,
                           @ApiParam("站内信的内容") @RequestParam("content") @NonNull String content) {

        HttpSession session=request.getSession(false);
        User user=(User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState()==1)
        {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        Message existsMessage=messageService.selectById(repliedId);
        if(existsMessage.getDeleteState()==1 || existsMessage==null)
        {
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }

        if(existsMessage.getPostUserId()==user.getId())
        {
            return AppResult.failed("不能给自己回复");
        }
        Message message=new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(existsMessage.getPostUserId());
        message.setContent(content);

        messageService.reply(repliedId,message);

        return AppResult.success();
    }
}
